<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>

<body>
    <!-- 父组件模板 -->
    <div id="app">
        <h1 class="title center">科泰聊天室</h1>
        <my-footer></my-footer>
    </div>

    <template id="footer">
        <div class="chat-window center">
            <div class="chat-messages">
                <!-- 正确使用 v-for 循环渲染消息 -->
                <div class="message" v-for="(item, index) in items" :key="index"
                    :class="{ 'received-message': !item.flg, 'sent-message': item.flg }">
                    <img :src="item.img" class="avatar">
                    <span class="message-content">{{ item.title }}</span>
                </div>
            </div>
            <!-- 子组件模板 -->
            <footer-item @add-click="addClick"></footer-item>
        </div>
    </template>

    <template id="footerItem">
        <div class="chat-input">
            <input type="text" placeholder="请输入消息..." v-model="newTask">
            <!-- 子组件按钮点击时触发 add-click 事件 -->
            <button @click="emitAddClick">发送</button>
        </div>
    </template>
    <script>
        // 子组件定义
        var footerItem = {
            template: "#footerItem",
            data: function () {
                return {
                    newTask: "" // 子组件可以有自己的新任务数据
                };
            },
            methods: {
                emitAddClick: function () {
                    this.$emit("add-click", this.newTask); // 向父组件发送事件和数据
                }
            }
        };

        // 父组件定义
        var footer = {
            template: "#footer",
            data: function () {
                return {
                    newTask: "",
                    items: [
                        { title: "好久不见！", img: "images/avt-01.png", flg: false },
                        { title: "是啊，好久不见了", img: "images/avt-02.png", flg: true },
                        { title: "最近怎么样？", img: "images/avt-01.png", flg: false },
                    ]
                };
            },
            methods: {
                addClick: function (newTask) {
                    if (newTask.trim() !== "") {
                        this.items.push({
                            title: newTask,
                            flg: true, // 表示发送的消息
                            img: "images/avt-02.png"
                        });
                        this.newTask = ""; // 清空输入框
                    }
                }
            },
            components: {
                "FooterItem": footerItem
            }
        };

        // Vue 实例
        new Vue({
            el: "#app",
            components: {
                "MyFooter": footer
            }
        });
    </script>
</body>

</html>